import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userApi } from '@/api/user'
import type { User } from '@/types'

export const useUserStore = defineStore('user', () => {
  // 状态
  const users = ref<User[]>([])
  const currentUser = ref<User | null>(null)
  const loading = ref(false)

  // 获取所有用户
  const fetchUsers = async () => {
    loading.value = true
    try {
      const response = await userApi.getAll()
      users.value = response
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取用户详情
  const fetchUser = async (id: number) => {
    loading.value = true
    try {
      const response = await userApi.getById(id)
      currentUser.value = response
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新用户信息
  const updateUser = async (id: number, userData: Partial<User>) => {
    loading.value = true
    try {
      const response = await userApi.update(id, userData)
      const index = users.value.findIndex(u => u.id === id)
      if (index !== -1) {
        users.value[index] = response
      }
      if (currentUser.value?.id === id) {
        currentUser.value = response
      }
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 删除用户
  const deleteUser = async (id: number) => {
    loading.value = true
    try {
      await userApi.delete(id)
      users.value = users.value.filter(u => u.id !== id)
      if (currentUser.value?.id === id) {
        currentUser.value = null
      }
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string) => {
    loading.value = true
    try {
      await userApi.changePassword(oldPassword, newPassword)
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 清空当前用户
  const clearCurrentUser = () => {
    currentUser.value = null
  }

  return {
    // 状态
    users,
    currentUser,
    loading,
    // 方法
    fetchUsers,
    fetchUser,
    updateUser,
    deleteUser,
    changePassword,
    clearCurrentUser
  }
})